const router = require('koa-router')()
const connection = require('./db'); // 导入数据库连接对象
const fs = require('fs');
router.get("/getteacherhome", async (ctx, next) => {
    let request = ctx.request;
    let reqquery = request.query;
    console.log(reqquery.studentid);
    console.log(reqquery);
  
    const studentId = reqquery.teacherid;
    const query7 = `SELECT * FROM \`teacher\` WHERE teacherid = ${studentId}`;
    console.log(query7);
    try {
      // 使用 Promise 封装数据库查询
      const queryAsync = () => {
        return new Promise((resolve, reject) => {
          connection.query(query7, function (error, results, fields) {
            if (error) {
              reject(error);
            } else {
              resolve(results);
            }
          });
        });
      };
  
      // 使用 await 等待查询结果
      const list = await queryAsync();
      //console.log(JSON.stringify(list));
      const parsedList = JSON.parse(JSON.stringify(list)); 
      console.log(parsedList);
  
    ctx.body = {
        list: parsedList,
    };
  // 打印整个集合
    } catch (error) {
      // 处理错误
      console.error(error);
      ctx.status = 500;
      ctx.body = "Internal Server Error";
    }
  });



  router.post('/changeteacherpassword', async (ctx, next) => {
    // 使用 ctx.query 访问查询参数
    const Id = ctx.request.body.id;
    const values = ctx.request.body.values;
    const newpassword = values.newpassword;
    console.log('收到的前端数据：', Id,newpassword);
    try {
      // 执行数据库更新操作
      const updateQuery = 'UPDATE teacher SET password = ? WHERE teacherid = ?';
      await connection.query(updateQuery, [newpassword, Id]);
  
      // 检查是否成功更新数据
      console.log('成功更新教师数据');
      ctx.body = '成功更新教师数据';
    } catch (error) {
      console.error('更新教师数据时出现错误：', error);
      ctx.status = 500;
      ctx.body = '更新教师数据时出现错误';
    }
  });

  router.post('/teacherupload', async (ctx) => {
    const file = ctx.request.files.file; // 文件将被存储在ctx.request.files中
    const studentId = ctx.request.body.studentid;
    const avatar = ctx.request.body.avatar;
    // 执行适当的文件处理逻辑
    const newFilename = file['newFilename'];
    console.log('新文件名:', newFilename, studentId, avatar);
    const filePath = './routes/uploads/' + avatar;
  
    // 添加条件判断，如果文件存在则执行删除操作
    fs.unlink(filePath, (err) => {
      if (err) {
        console.error('文件删除失败', err);
        return;
      }
      console.log('文件删除成功');
    });
  
    await connection.query('UPDATE teacher SET avatar = ? WHERE teacherid = ?', [newFilename, studentId]);
    ctx.body = 'File uploaded successfully';
  })
  
  router.post('/courseupload', async (ctx) => {
    const file = ctx.request.files.file; // 文件将被存储在ctx.request.files中
    const studentId = ctx.request.body.studentid;
    const avatar = ctx.request.body.avatar;
    // 执行适当的文件处理逻辑
    const newFilename = file['newFilename'];
    console.log('新文件名:', newFilename, studentId, avatar);
    const filePath = './routes/uploads/' + avatar;
  
    // 添加条件判断，如果文件存在则执行删除操作
    fs.unlink(filePath, (err) => {
      if (err) {
        console.error('文件删除失败', err);
        return;
      }
      console.log('文件删除成功');
    });
  
    await connection.query('UPDATE course SET img = ? WHERE courseid = ?', [newFilename, studentId]);
    ctx.body = 'File uploaded successfully';
  })
  



  router.post('/teacherAssignment', async (ctx, next) => {
    const { courseid, teacherid } = ctx.request.body;
    console.log(courseid, teacherid);
  
    try {
      // 检查 courseid 是否存在于表 course
      const courseCheckResult = await new Promise((resolve, reject) => {
        connection.query('SELECT * FROM course WHERE courseid = ?', [courseid], (error, result) => {
          if (error) {
            reject(error);
          } else {
            resolve(result);
          }
        });
      });
  
      if (courseCheckResult.length === 0) {
        // 如果 courseid 不存在，返回相应信息
        ctx.status = 404;
        ctx.body = { message: '课程不存在' };
        return;
      }
  
      // 检查 teacherid 是否存在于表 teacher
      const teacherCheckResult = await new Promise((resolve, reject) => {
        connection.query('SELECT * FROM teacher WHERE teacherid = ?', [teacherid], (error, result) => {
          if (error) {
            reject(error);
          } else {
            resolve(result);
          }
        });
      });
  
      if (teacherCheckResult.length === 0) {
        // 如果 teacherid 不存在，返回相应信息
        ctx.status = 404;
        ctx.body = { message: '教师不存在' };
        return;
      }
  
      // 检查 teacher-course 表中是否已存在指定的 courseid 和 teacherid
      const teacherCourseCheckResult = await new Promise((resolve, reject) => {
        connection.query('SELECT * FROM `teacher-course` WHERE courseid = ? AND teacherid = ?', [courseid, teacherid], (error, result) => {
          if (error) {
            reject(error);
          } else {
            resolve(result);
          }
        });
      });
  
      if (teacherCourseCheckResult.length > 0) {
        // 如果指定的 courseid 和 teacherid 已存在，返回相应信息
        ctx.status = 409;
        ctx.body = { message: '课程和教师已关联' };
        return;
      }
  
      // 将courseid, teacherid添加到表teacher-course
      const insertResult = await new Promise((resolve, reject) => {
        connection.query('INSERT INTO `teacher-course` (courseid, teacherid) VALUES (?, ?)', [courseid, teacherid], (error, result) => {
          if (error) {
            reject(error);
          } else {
            resolve(result);
          }
        });
      });
  
      console.log(insertResult);
  
      if (insertResult.affectedRows > 0) {
        ctx.status = 200;
        ctx.body = { message: '分配成功' };
      } else {
        ctx.status = 500;
        ctx.body = { message: '内部服务器错误' };
      }
  
    } catch (error) {
      console.error('错误:', error);
      ctx.status = 500;
      ctx.body = { message: '内部服务器错误' };
    }
  });
  

module.exports = router;